<?php

namespace app\admin\quick\resource;


use app\common\model\SystemConfigGroup;
use app\common\service\common\BuildGroupViewService;
use quick\admin\annotation\AdminAuth;
use quick\admin\components\Component;
use quick\admin\components\layout\Content;
use quick\admin\form\Form;
use quick\admin\library\service\SystemService;


/**
 * 系统配置参数
 * @AdminAuth(auth=true,menu=true,login=true,title="系统参数")
 * Class SystemConfig
 * @package app\admin\quick\resource
 */
class SystemConfig extends Resource
{
    /**
     * 标题
     *
     * @var string
     */
    protected $title = '系统配置';

    /**
     * @var string
     */
    protected $description = "可以在此增改系统的变量和分组,也可以自定义分组和变量";

    /**
     * 关联模型 app\\common\\model\\DemoArticle
     *
     * @var string
     */
    protected static $model = 'app\common\model\SystemConfig';


    /**
     * 可搜索字段
     * @var array
     */
    protected static $search = ["id"];


    protected $topGroupList;
    protected $configList;


    /**
     *
     * @return Content
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function display()
    {
        $tabKey = 'group';
        $groupList = $this->topGroupList;

        $defaultGroupId = $this->request->param($tabKey,'base');

        $topTabs = Component::tabs()
            ->top()
            ->isFilter()
            ->tabKey($tabKey)
            ->removeBottom();

        $currentTopGroup = null;
        foreach ($groupList as $group) {
            if(empty($currentTopGroup) && ($group['id'] == $defaultGroupId || empty($defaultGroupId)) ){
                $currentTopGroup = $group;
                $defaultGroupId = $group['id'];
            }
            $topTabs->tab($group['title'],'',$group['id']);
        }
        $topTabs->default($defaultGroupId);



        // 获取二级tab配置
        if($currentTopGroup && !empty($currentTopGroup['form'])){
            $subGroupList = $currentTopGroup['sub'] ?? [];
        }else{
            $subGroupList = SystemConfigGroup::where([
                'status' => 1,
                'parent_id' => $defaultGroupId,
            ])->order('sort desc,id asc')->select()->toArray();
        }


        if(empty($subGroupList) && $currentTopGroup){
            // 没有子group 直接显示
            $content = $this->getGroupForm($currentTopGroup['group']);

        }else{
            // 设置子group
            $tabs = Component::tabs()->borderCard();
            foreach ($subGroupList as  $tab) {
                $form = $this->getGroupForm($tab['group']);
                $tabs->tab($tab['title'], $form);
            }
            $tabs->default('0');
            $content = $tabs;
        }



        return Component::content()
            ->title($this->title())
            ->description($this->description())
            ->children($topTabs, 'tools')
            ->body($content);
    }



    /**
     * @AdminAuth(title="系统设置",auth=true,menu=true,login=true,log=true)
     * @return \think\response\Json
     * @throws \quick\admin\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function list()
    {
        saveDataAuth();
        $request = request();
        $group = request()->get('_group');
        $config = SystemService::instance();
        if (!empty($group)) {

            $configList = $this->configList;
            $fields = $configList[$group] ?? [];
            if (!empty($fields) && is_array($fields)) {

                $service = new BuildGroupViewService();
                $form = $service->getGroupDataForm($fields);
                $data = $form->getSubmitData($request, 3);
                foreach ($fields as $field) {
                    if (isset($data[$field['name']])) {
                        $config->set(
                            $field['group'] . "." . $field['name'],
                            $data[$field['name']],
                            $this->plugin(),
                            $field['type']
                        );
                    }
                }


            }else if($fields instanceof Form){

                $data = $fields->getSubmitData($request, 3);
                foreach ($data as $key => $val) {
                    $config->set(
                        $group . "." . $key,
                        $val,
                        $this->plugin(),
                        'string',
                    ['config_type' => 'code']);
                }

            }
            return $this->success('设置成功');
        }
        return $this->error('设置失败');
    }


    protected function getGroupForm(string $group)
    {

        $fields = $this->configList[$group] ?? [];
        if($fields instanceof Form){
            $form = $fields;
        }else{
            $service = new BuildGroupViewService();
            $form = $service->getGroupDataForm($fields);
            $form->style('max-width','600px');
        }
        $form->url($this->createUrl("list?_group={$group}"));
        $form->hideCancel();
        return $form;

    }

    protected function init()
    {


        $configList = \app\common\model\SystemConfig::getConfigList(['plugin' => $this->plugin()]);
        $this->configList = $configList;

        // 添加配置组
        $form = Form::make();
        $form->style('max-width','500px');
        $form->image('app_logo','系统logo');
        $form->image('loginBanner','登录页面左侧图片');
        $form->image('loginBgImage','登录页面背景图片');
//        $form->text('site_name','网站名称')->help('网站名称将显示在浏览器的标签上');
        $form->text('app_name','系统名称')->help('管理程序名称显示在后台左上标题处');
        $form->text('app_version','后台程序版本');


        $form->text('copyrightDates','版权时间');
        $form->text('copyright','网站版权信息');
        $form->text('website','备案查询网址');
        $group = $this->builGroup('base','系统配置',$form);

        $form = Form::make();
        $form->style('max-width','500px');
        $form->text('storage_dir_prefix','文件前缀')->help('填写文件前缀，文件生成路径 upload/{文件前缀}/文件地址');
        $form->text('allow_exts','允许上传类型')->help('填写允许文件上传类型多个用,号隔开');
        $storageGroup = $this->builGroup('storage','上传配置',$form);

        $this->topGroupList[] = $group;
        $this->topGroupList[] = $storageGroup;


        $groupList = SystemConfigGroup::where([
            'status' => 1,
            'parent_id' => 0,
        ])->order('sort desc,id asc')->select()->toArray();
        $this->topGroupList = array_merge($this->topGroupList , $groupList);


    }

    private function plugin()
    {
        return 'admin';
    }

    private function builGroup(string $group,string $name,Form  $form)
    {

        $data = $this->configList[$group] ?? [];
        $formValue = [];
        foreach ($data as $item){
            $formValue[$item['name']] = $item['value'];
        }

        $form->resolve($formValue);
        $this->configList[$group] = $form;
        return [
            'id' => $group,
            'group' => $group,
            'title' => $name,
            'form' => $form,
        ];
    }




}
